<template>
  <div class="admin-dashboard">
    <el-container>
      <el-main>
        <!-- 统计卡片 -->
        <div class="stats-grid">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon orders">
                <el-icon size="32">
                  <Document />
                </el-icon>
              </div>
              <div class="stat-info">
                <h3>今日订单</h3>
                <p class="stat-number">{{ stats.todayOrders }}</p>
                <p class="stat-change">
                  <span :class="stats.orderChange >= 0 ? 'positive' : 'negative'">
                    {{ stats.orderChange >= 0 ? '+' : '' }}{{ stats.orderChange }}%
                  </span>
                  较昨日
                </p>
              </div>
            </div>
          </el-card>

          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon revenue">
                <el-icon size="32">
                  <Money />
                </el-icon>
              </div>
              <div class="stat-info">
                <h3>今日收入</h3>
                <p class="stat-number">¥{{ stats.todayRevenue }}</p>
                <p class="stat-change">
                  <span :class="stats.revenueChange >= 0 ? 'positive' : 'negative'">
                    {{ stats.revenueChange >= 0 ? '+' : '' }}{{ stats.revenueChange }}%
                  </span>
                  较昨日
                </p>
              </div>
            </div>
          </el-card>

          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon users">
                <el-icon size="32">
                  <User />
                </el-icon>
              </div>
              <div class="stat-info">
                <h3>新增用户</h3>
                <p class="stat-number">{{ stats.newUsers }}</p>
                <p class="stat-change">
                  <span :class="stats.userChange >= 0 ? 'positive' : 'negative'">
                    {{ stats.userChange >= 0 ? '+' : '' }}{{ stats.userChange }}%
                  </span>
                  较昨日
                </p>
              </div>
            </div>
          </el-card>

          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon products">
                <el-icon size="32">
                  <Goods />
                </el-icon>
              </div>
              <div class="stat-info">
                <h3>商品总数</h3>
                <p class="stat-number">{{ stats.totalProducts }}</p>
                <p class="stat-change">
                  <span class="positive">+{{ stats.newProducts }}</span>
                  本月新增
                </p>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 图表区域 -->
        <div class="charts-section">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-card class="chart-card">
                <template #header>
                  <span>销售趋势</span>
                  <el-select v-model="salesPeriod" size="small" style="float: right; width: 120px">
                    <el-option label="最近7天" value="7" />
                    <el-option label="最近30天" value="30" />
                    <el-option label="最近90天" value="90" />
                  </el-select>
                </template>
                <div class="chart-container">
                  <div ref="salesChartRef" class="chart"></div>
                </div>
              </el-card>
            </el-col>

            <el-col :span="8">
              <el-card class="chart-card">
                <template #header>
                  <span>商品分类占比</span>
                </template>
                <div class="chart-container">
                  <div ref="categoryChartRef" class="chart"></div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 最新订单和缺货库存 -->
        <div class="recent-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="recent-card">
                <template #header>
                  <span>最新订单</span>
                  <el-button text @click="viewAllOrders">查看全部</el-button>
                </template>
                <el-table :data="recentOrders" v-loading="ordersLoading" size="small">
                  <el-table-column label="订单号" prop="orderSn" width="180" />
                  <el-table-column label="收货人" prop="receiverName" width="100" />
                  <el-table-column label="总金额" prop="totalAmount" width="100">
                    <template #default="{ row }"> ¥{{ row.totalAmount }} </template>
                  </el-table-column>
                  <el-table-column label="实付金额" prop="payAmount" width="100">
                    <template #default="{ row }"> ¥{{ row.payAmount }} </template>
                  </el-table-column>
                  <el-table-column label="状态" prop="status" width="100">
                    <template #default="{ row }">
                      <el-tag :type="getStatusType(row.status)" size="small">{{ getStatusText(row.status) }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="创建时间" prop="createdAt" width="160">
                    <template #default="{ row }">
                      {{ formatDate(row.createdAt) }}
                    </template>
                  </el-table-column>
                </el-table>
                <div v-if="recentOrders.length === 0 && !ordersLoading" class="empty-state">
                  <el-icon size="48" color="#c0c4cc">
                    <Document />
                  </el-icon>
                  <p>暂无订单数据</p>
                </div>
              </el-card>
            </el-col>

            <el-col :span="12">
              <el-card class="recent-card">
                <template #header>
                  <span>缺货库存管理</span>
                  <el-button text @click="viewAllStock">查看全部</el-button>
                </template>
                <el-table :data="lowStockItems" v-loading="stockLoading" size="small">
                  <el-table-column label="商品名称" prop="productName" width="150" />
                  <el-table-column label="尺码" prop="sizeName" width="80" />
                  <el-table-column label="颜色" prop="colorName" width="80" />
                  <el-table-column label="库存数量" prop="stockQuantity" width="100">
                    <template #default="{ row }">
                      <el-tag 
                        :type="row.stockQuantity === 0 ? 'danger' : 'warning'" 
                        size="small"
                      >
                        {{ row.stockQuantity }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="价格" prop="price" width="100">
                    <template #default="{ row }"> ¥{{ row.price }} </template>
                  </el-table-column>
                </el-table>
                <div v-if="lowStockItems.length === 0 && !stockLoading" class="empty-state">
                  <el-icon size="48" color="#c0c4cc">
                    <Goods />
                  </el-icon>
                  <p>暂无缺货商品</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 快捷操作 -->
        <div class="quick-actions">
          <el-card>
            <template #header>
              <span>快捷操作</span>
            </template>
            <div class="actions-grid">
              <el-button
                v-for="action in quickActions"
                :key="action.name"
                :type="action.type as any"
                :icon="action.icon"
                @click="action.handler"
              >
                {{ action.name }}
              </el-button>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
// 组件名称
defineOptions({
  name: 'AdminDashboard'
})

import { ref, onMounted, reactive } from 'vue'
import { orderService } from '@/api'
import { productService } from '@/api'
import { reportService } from '@/api/reportService'
import { useRouter } from 'vue-router'
import { createLogger } from '@/utils/logger'
import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import {
  Document,
  Money,
  User,
  Goods,
  Plus,
  Upload,
} from '@element-plus/icons-vue'

// 注册 ECharts 组件
echarts.use([
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  CanvasRenderer,
])

const router = useRouter()
const dashboardLogger = createLogger('Dashboard')

// 图表引用
const salesChartRef = ref<HTMLDivElement | null>(null)
const categoryChartRef = ref<HTMLDivElement | null>(null)

// 响应式数据
const salesPeriod = ref('7')
const stats = ref({
  todayOrders: 0,
  orderChange: 0,
  todayRevenue: 0,
  revenueChange: 0,
  newUsers: 0,
  userChange: 0,
  totalProducts: 0,
  newProducts: 0,
})

interface OrderRow {
  orderId: number
  orderSn: string
  userId: number
  totalAmount: number
  payAmount: number
  status: number
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  createdAt: string
  updatedAt: string
}

interface StockRow {
  skuId?: number
  shoeId: number
  sizeId: number
  colorId: number
  price: number
  discountPrice?: number
  stockQuantity: number
  productName?: string
  sizeName?: string
  colorName?: string
  shoes?: { name: string }
  size?: { shoeSize: string }
  color?: { colorName: string }
}

const recentOrders = ref<OrderRow[]>([])
const ordersLoading = ref(false)
const lowStockItems = ref<StockRow[]>([])
const stockLoading = ref(false)

// 图表数据
const salesData = reactive({
  dates: [],
  orderCounts: [],
  dailyGmv: []
})

const categoryData = reactive({
  categories: [],
  counts: []
})

// 快捷操作
const quickActions = [
  {
    name: '添加商品',
    type: 'primary',
    icon: Plus,
    handler: () => router.push('/admin/products/add'),
  },
  {
    name: '订单管理',
    type: 'success',
    icon: Document,
    handler: () => router.push('/admin/orders'),
  },
  {
    name: '用户管理',
    type: 'warning',
    icon: User,
    handler: () => router.push('/admin/users'),
  },
  {
    name: '批量导入',
    type: 'info',
    icon: Upload,
    handler: () => handleBatchImport(),
  },
]

// 方法
const loadDashboardData = async () => {
  try {
    // 加载仪表板概览数据
    const dashboardData = await reportService.getDashboardData()
    
    // 加载销售趋势数据
    const salesTrendData = await reportService.getSalesTrend()
    
    // 加载品牌表现数据（用于分类占比）
    const brandData = await reportService.getBrandPerformance()
    
    // 更新统计数据
    stats.value = {
      todayOrders: dashboardData.todayOrders ?? 0,
      orderChange: dashboardData.orderChange ?? 0,
      todayRevenue: dashboardData.todayGmv ?? 0,
      revenueChange: dashboardData.revenueChange ?? 0,
      newUsers: dashboardData.yesterdayNewUsers ?? 0, // 使用昨日新增用户数
      userChange: dashboardData.userChange ?? 0,
      totalProducts: dashboardData.totalProducts ?? 0,
      newProducts: dashboardData.yesterdayNewProducts ?? 0, // 使用昨日新增商品数
    }
    
    // 更新销售数据
    Object.assign(salesData, {
      dates: salesTrendData.dates || [],
      orderCounts: salesTrendData.orderCounts || [],
      dailyGmv: salesTrendData.dailyGmv || []
    })
    
    // 更新分类数据（使用品牌数据）
    Object.assign(categoryData, {
      categories: brandData.brandNames || [],
      counts: brandData.productCounts || []
    })
    
    // 加载最新订单
    try {
      ordersLoading.value = true
      const recentRes = await orderService.getOrdersList(1, 10)
      dashboardLogger.debug('API响应数据:', recentRes.data)

      // 统一处理不同的响应格式
      let ordersList: unknown[] = []
      let totalCount = 0

      if (recentRes.data) {
        // 格式1: { code: 200, msg: "查询成功", data: { orders: [...], total: 123 } }
        if (recentRes.data.code === 200 && recentRes.data.data) {
          const data = recentRes.data.data as unknown as Record<string, unknown>
          ordersList = (data.orders as unknown[]) || (data.list as unknown[]) || []
          totalCount = (data.total as number) || 0
        }
        // 格式2: { success: true, data: { orders: [...], total: 123 } }
        else if ('success' in recentRes.data && recentRes.data.success === true && 'data' in recentRes.data && recentRes.data.data) {
          const data = recentRes.data.data as unknown as Record<string, unknown>
          ordersList = (data.orders as unknown[]) || (data.list as unknown[]) || []
          totalCount = (data.total as number) || 0
        }
        // 格式3: 直接返回数据数组
        else if (Array.isArray(recentRes.data)) {
          ordersList = recentRes.data
          totalCount = recentRes.data.length
        }
        // 格式4: 直接返回数据对象
        else if (typeof recentRes.data === 'object' && recentRes.data !== null) {
          const data = recentRes.data as unknown as Record<string, unknown>
          if (data.orders || data.list) {
            ordersList = (data.orders as unknown[]) || (data.list as unknown[]) || []
            totalCount = (data.total as number) || ordersList.length
          }
        }
      }

      dashboardLogger.debug('解析后的订单数据:', {
        ordersList,
        totalCount
      })

      if (ordersList.length > 0) {
        // 确保数据格式正确，处理后端返回的Order实体结构
        recentOrders.value = ordersList.map((order: unknown) => {
          // 处理可能的嵌套结构
          const orderObj = order as Record<string, unknown>
          const orderData = (orderObj.order as Record<string, unknown>) || orderObj
          
          return {
            orderId: Number(orderData.orderId || orderData.id || orderObj.orderId || 0),
            orderSn: String(orderData.orderSn || orderData.orderNumber || orderObj.orderSn || ''),
            userId: Number(orderData.userId || orderData.user_id || orderObj.userId || 0),
            totalAmount: Number(orderData.totalAmount || orderData.total_amount || orderObj.totalAmount || 0),
            payAmount: Number(orderData.payAmount || orderData.pay_amount || orderObj.payAmount || 0),
            status: Number(orderData.status || orderObj.status || 0),
            receiverName: String(orderData.receiverName || orderData.receiver_name || orderObj.receiverName || ''),
            receiverPhone: String(orderData.receiverPhone || orderData.receiver_phone || orderObj.receiverPhone || ''),
            receiverAddress: String(orderData.receiverAddress || orderData.receiver_address || orderObj.receiverAddress || ''),
            createdAt: String(orderData.createdAt || orderData.created_at || orderObj.createdAt || ''),
            updatedAt: String(orderData.updatedAt || orderData.updated_at || orderObj.updatedAt || ''),
          }
        })
      } else {
        recentOrders.value = []
      }
      
      dashboardLogger.debug('最终订单数据:', recentOrders.value)
    } catch (error) {
      dashboardLogger.error('加载最新订单失败:', error)
      recentOrders.value = []
    } finally {
      ordersLoading.value = false
    }
    
    // 加载缺货库存数据
    await loadLowStockData()
    
    // 初始化图表
    initSalesChart()
    initCategoryChart()
  } catch (error) {
    dashboardLogger.error('加载仪表板数据失败:', error)
  }
}

// 加载缺货库存数据
const loadLowStockData = async () => {
  try {
    stockLoading.value = true
    const res = await productService.getStockList()
    
    if (res.data && (res.data as unknown as Record<string, unknown>).code === 200) {
      const stockList = (res.data as unknown as Record<string, unknown>).data as StockRow[] || []
      
      // 过滤出库存不足的商品（库存 <= 10）
      const lowStock = stockList.filter((item: StockRow) => item.stockQuantity <= 10)
      
      // 按库存数量升序排序
      lowStock.sort((a: StockRow, b: StockRow) => a.stockQuantity - b.stockQuantity)
      
      // 只显示前10个
      lowStockItems.value = lowStock.slice(0, 10).map((item: StockRow) => ({
        skuId: item.skuId,
        shoeId: item.shoeId,
        sizeId: item.sizeId,
        colorId: item.colorId,
        price: item.price,
        discountPrice: item.discountPrice,
        stockQuantity: item.stockQuantity,
        productName: item.shoes?.name || '未知商品',
        sizeName: item.size?.shoeSize || '未知尺码',
        colorName: item.color?.colorName || '未知颜色'
      }))
    }
  } catch (error) {
    dashboardLogger.error('加载缺货库存数据失败:', error)
    lowStockItems.value = []
  } finally {
    stockLoading.value = false
  }
}

// 初始化销售趋势图表
const initSalesChart = () => {
  if (!salesChartRef.value) return
  
  const chart = echarts.init(salesChartRef.value)
  chart.setOption({
    tooltip: { 
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: { 
      data: ['订单数', 'GMV(¥)'],
      bottom: 0
    },
    grid: { 
      left: 30, 
      right: 20, 
      top: 20, 
      bottom: 50 
    },
    xAxis: { 
      type: 'category', 
      data: salesData.dates,
      axisLabel: { rotate: 45 }
    },
    yAxis: [
      { 
        type: 'value', 
        name: '订单数',
        position: 'left'
      },
      { 
        type: 'value', 
        name: 'GMV(¥)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 0,
        smooth: true,
        data: salesData.orderCounts,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: 'GMV(¥)',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        data: salesData.dailyGmv,
        itemStyle: { color: '#67C23A' }
      }
    ]
  })
}

// 初始化分类占比图表
const initCategoryChart = () => {
  if (!categoryChartRef.value) return
  
  const chart = echarts.init(categoryChartRef.value)
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '商品数量',
        type: 'pie',
        radius: '60%',
        data: categoryData.categories.map((category, index) => ({
          name: category,
          value: categoryData.counts[index]
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

const getStatusType = (status: number): 'warning' | 'primary' | 'success' | 'danger' | 'info' => {
  const statusMap: Record<number, 'warning' | 'primary' | 'success' | 'danger' | 'info'> = {
    0: 'warning',   // 待付款
    1: 'primary',   // 待发货
    2: 'info',      // 运输中
    3: 'success',   // 已完成
    4: 'danger',    // 已取消
    5: 'warning',   // 申请退货
    6: 'info',      // 已退货
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '待付款',
    1: '待发货',
    2: '运输中',
    3: '已完成',
    4: '已取消',
    5: '申请退货',
    6: '已退货',
  }
  return statusMap[status] || '未知状态'
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const viewAllOrders = () => {
  router.push('/admin/orders')
}

const viewAllStock = () => {
  router.push('/admin/stock')
}

const handleBatchImport = () => {
  // TODO: 处理批量导入
  dashboardLogger.info('批量导入')
}

// 组件挂载时加载数据
onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.admin-dashboard {
  padding: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  border-radius: 12px;
  color: white;
}

.stat-icon.orders {
  background: linear-gradient(135deg, #ff5a00 0%, #ff0036 100%);
}

.stat-icon.revenue {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.users {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.products {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info h3 {
  font-size: 14px;
  font-weight: 500;
  color: #909399;
  margin: 0 0 8px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #303133;
  margin: 0 0 4px 0;
}

.stat-change {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.stat-change .positive {
  color: #67c23a;
}

.stat-change .negative {
  color: #f56c6c;
}

.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 320px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

.recent-section {
  margin-bottom: 24px;
}

.recent-card {
  height: auto;
  min-height: 400px;
}

.recent-section .el-col {
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #c0c4cc;
}

.empty-state p {
  margin: 16px 0 0 0;
  font-size: 14px;
}

.quick-actions {
  margin-bottom: 20px;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .charts-section .el-col {
    margin-bottom: 20px;
  }

  .recent-section .el-col {
    margin-bottom: 20px;
  }

  .actions-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
